import requests
from collections import defaultdict
from datetime import datetime, timedelta
import re

def get_week_range():
    today = datetime.now()
    # 本周一
    this_monday = today - timedelta(days=today.weekday())
    # 上周一
    last_monday = this_monday - timedelta(days=7)
    return last_monday, this_monday

last_monday, this_monday = get_week_range()
# 构造时间字符串
last_monday_str = last_monday.strftime('%Y-%m-%dT00:00:00+08:00')
this_monday_str = this_monday.strftime('%Y-%m-%dT00:00:00+08:00')
# 仅日期部分用于md文件开头
last_monday_date = last_monday.strftime('%Y-%m-%d')
this_monday_date = this_monday.strftime('%Y-%m-%d')

def escape_markdown(text):
    """转义markdown中的特殊字符"""
    if not text:
        return ''
    # 需要转义的字符：\ ` * _ { } [ ] ( ) # + - . !
    special_chars = ['\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '#', '+', '-', '.', '!']
    escaped_text = text
    for char in special_chars:
        escaped_text = escaped_text.replace(char, '\\' + char)
    return escaped_text

def fetch_issues(sig_repos):
    result = defaultdict(dict)
    for sig_name, repos in sig_repos.items():
        sig_issues={}

        for repo in repos:
            url = f"https://api.gitcode.com/api/v5/repos/openUBMC/{repo}/issues"
            params = {
                "access_token":"ah11z3XPsv4z-PDxFpnHTWBr",
                "state":"closed",
                "updated_after": last_monday_str,
                "updated_before": this_monday_str
            }

            try:
                response = requests.get(
                    url,
                    headers={'Accept':'application/json'},
                    params=params,
                    timeout=10
                )
                response.raise_for_status()

                issues = response.json()
                sig_issues[repo]={
                    'count':len(issues),
                    'issues':issues
                }
            except requests.exceptions.RequestException as e:
                print("请求失败:")
                print({str(e)})
            except ValueError as e:
                print('不合法的json响应')  

        result[sig_name] = sig_issues

    return dict(result)  

def process_sig_groups(api_data):
    grouped_repos = defaultdict(list)
    
    for group in api_data:
        mailing_list = group.get('mailing_list','')
        sig_name = mailing_list.split('@')[0] if '@' in mailing_list else group['sig_name']

        for repo in group.get('repos',[]):
            clean_repo = repo.strip().replace(' ','')
            if '/' not in clean_repo:
                continue
            _,repo_name = clean_repo.split('/', 1)

            if repo_name not in grouped_repos[sig_name]:
                grouped_repos[sig_name].append(repo_name)
    return dict(grouped_repos)



def fetch_and_process():
    api_url = "https://openUBMC.cn/api-dsapi/query/sig/info"

    try:
        response = requests.get(
            api_url,
            params={"community" : "openubmc"},
            verify=False,
            timeout=10
        )
        response.raise_for_status()
        
        if response.json().get('code') != 200:
            raise ValueError("状态码异常")
        
        return process_sig_groups(response.json()['data'])
    
    except Exception as e:
        print(f"数据处理失败")
        return {}
    
sig_repos = fetch_and_process()

issues_data = fetch_issues(sig_repos)

total_issues = sum(
    repo_data.get('count',0)
    for sig in issues_data.values()
    for repo_data in sig.values()
)

def fetch_created_issues(sig_repos, create_after, create_before):
    result = defaultdict(dict)
    for sig_name, repos in sig_repos.items():
        sig_issues = {}
        for repo in repos:
            url = f"https://api.gitcode.com/api/v5/repos/openUBMC/{repo}/issues"
            params = {
                "access_token": "ah11z3XPsv4z-PDxFpnHTWBr",
                "created_after": create_after,
                "created_before": create_before
                # "state":"open",
            }
            try:
                response = requests.get(
                    url,
                    headers={'Accept': 'application/json'},
                    params=params,
                    timeout=10
                )
                response.raise_for_status()
                issues = response.json()
                sig_issues[repo] = {
                    'count': len(issues),
                    'issues': issues
                }
            except requests.exceptions.RequestException as e:
                print("请求失败:")
                print({str(e)})
            except ValueError as e:
                print('不合法的json响应')
        result[sig_name] = sig_issues
    return dict(result)

created_issues_data = fetch_created_issues(sig_repos, last_monday_str, this_monday_str)

def format_md_date(dt_str):
    if not dt_str:
        return ''
    try:
        # 兼容ISO格式
        dt = datetime.fromisoformat(dt_str.replace('Z', '+00:00'))
        return dt.strftime('%m-%d')
    except Exception:
        return dt_str[:10] if '-' in dt_str else dt_str

def generate_sig_reports(issues_data):
    markdown_content = []
    sig_index = 1
    for sig_name in sorted(issues_data.keys()):
        repos = issues_data[sig_name]
        total_issues = 0
        table_rows = []
        repo_issues = {}
        for repo_name, repo_data in repos.items():
            if not isinstance(repo_data, dict):
                continue
            issues = repo_data.get('issues', [])
            count = len(issues)
            if count > 0:
                total_issues += count
                # 按关闭时间降序排列
                sorted_issues = sorted(issues, key=lambda x: x.get('updated_at', ''), reverse=True)
                repo_issues[repo_name] = sorted_issues
        for repo_name, issues in repo_issues.items():
            for idx, issue in enumerate(issues):
                repo_cell = repo_name if idx == 0 else ""
                title = escape_markdown(issue.get('title', '无标题'))
                url = issue.get('html_url', '#')
                closed_time = format_md_date(issue.get('updated_at', ''))
                table_rows.append(f"|{repo_cell}|[{title}]({url})|{closed_time}")
        header = f"# {sig_name}组"
        if total_issues > 0:
            header += f"\n## 1. 关闭的issue\n本周共关闭{total_issues}个issue"
            markdown_content.extend([f"\n{header}\n", "|代码仓名称|issue标题|关闭时间|\n|-----|-----|-----|", *table_rows, ""])
        else:
            header += f"\n## 1. 关闭的issue\nsig组-{sig_name}本周没有关闭的issue"
            markdown_content.append(header)
        sig_index += 1
    return "\n".join(markdown_content)

def generate_created_issues_reports(created_issues_data):
    markdown_content = []
    sig_index = 1
    for sig_name in sorted(created_issues_data.keys()):
        repos = created_issues_data[sig_name]
        total_issues = 0
        table_rows = []
        repo_issues = {}
        for repo_name, repo_data in repos.items():
            if not isinstance(repo_data, dict):
                continue
            issues = repo_data.get('issues', [])
            count = len(issues)
            if count > 0:
                total_issues += count
                # 按创建时间降序排列
                sorted_issues = sorted(issues, key=lambda x: x.get('created_at', ''), reverse=True)
                repo_issues[repo_name] = sorted_issues
        for repo_name, issues in repo_issues.items():
            for idx, issue in enumerate(issues):
                repo_cell = repo_name if idx == 0 else ""
                title = escape_markdown(issue.get('title', '无标题'))
                url = issue.get('html_url', '#')
                created_time = format_md_date(issue.get('created_at', ''))
                table_rows.append(f"|{repo_cell}|[{title}]({url})|{created_time}")
        header = f"## 2. 新增的issue"
        if total_issues > 0:
            header += f"\n本周共新增{total_issues}个issue"
            markdown_content.extend([f"\n{header}\n", "|代码仓名称|issue标题|创建时间|\n|-----|-----|-----|", *table_rows, ""])
        else:
            header += f"\nsig组-{sig_name}本周没有新增的issue"
            markdown_content.append(header)
        sig_index += 1
    return "\n".join(markdown_content)

md_doc = generate_sig_reports(issues_data)
created_md_doc = generate_created_issues_reports(created_issues_data)

week_start, week_end = get_week_range()

with open("sig_reports.md", "w", encoding="utf-8") as f:
    # 统计总关闭和新增issue数量
    total_closed = sum(len(repo_data.get('issues', [])) for sig in issues_data.values() for repo_data in sig.values() if isinstance(repo_data, dict))
    total_created = sum(len(repo_data.get('issues', [])) for sig in created_issues_data.values() for repo_data in sig.values() if isinstance(repo_data, dict))
    f.write(f"本周({last_monday_date}- {this_monday_date})，openUBMC项目共关闭{total_closed}个issue，新增{total_created}个issue\n")
    for sig_name in sorted(issues_data.keys()):
        # 一级标题
        f.write(f"\n# {sig_name}组\n")
        # 关闭issue
        repos = issues_data[sig_name]
        total_closed = sum(len(repo_data.get('issues', [])) for repo_data in repos.values() if isinstance(repo_data, dict))
        f.write("## 1. 关闭的issue\n")
        if total_closed > 0:
            f.write(f"本周共关闭{total_closed}个issue\n")
            f.write("|代码仓名称|issue标题|关闭时间|\n|-----|-----|-----|\n")
            for repo_name, repo_data in repos.items():
                if not isinstance(repo_data, dict):
                    continue
                # 按关闭时间降序排列
                sorted_issues = sorted(repo_data.get('issues', []), key=lambda x: x.get('updated_at', ''), reverse=True)
                for idx, issue in enumerate(sorted_issues):
                    repo_cell = repo_name if idx == 0 else ""
                    title = escape_markdown(issue.get('title', '无标题'))
                    url = issue.get('html_url', '#')
                    closed_time = format_md_date(issue.get('updated_at', ''))
                    f.write(f"|{repo_cell}|[{title}]({url})|{closed_time}\n")
        else:
            f.write(f"sig组-{sig_name}本周没有关闭的issue\n")
        # 新增issue
        f.write("## 2. 新增的issue\n")
        created_repos = created_issues_data.get(sig_name, {})
        total_created = sum(len(repo_data.get('issues', [])) for repo_data in created_repos.values() if isinstance(repo_data, dict))
        if total_created > 0:
            f.write(f"本周共新增{total_created}个issue\n")
            f.write("|代码仓名称|issue标题|创建时间|\n|-----|-----|-----|\n")
            for repo_name, repo_data in created_repos.items():
                if not isinstance(repo_data, dict):
                    continue
                # 按创建时间降序排列
                sorted_issues = sorted(repo_data.get('issues', []), key=lambda x: x.get('created_at', ''), reverse=True)
                for idx, issue in enumerate(sorted_issues):
                    repo_cell = repo_name if idx == 0 else ""
                    title = escape_markdown(issue.get('title', '无标题'))
                    url = issue.get('html_url', '#')
                    created_time = format_md_date(issue.get('created_at', ''))
                    f.write(f"|{repo_cell}|[{title}]({url})|{created_time}\n")
        else:
            f.write(f"sig组-{sig_name}本周没有新增的issue\n")

print("报告已生成到 sig_reports.md 文件")




